package com.entor.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.entor.model.Files;
import com.entor.model.Msg;
import com.entor.model.Notice;
import com.entor.service.BaseServiceI;
import com.entor.util.FileIOUtil;

@Controller
@RequestMapping("/nc")
public class NoticeController extends BaseController<Notice>{
	
	@Resource(name="noticeService")
	private BaseServiceI<Notice> nbsi;
	@Resource(name="filesService")
	private BaseServiceI<Files> fbsi;
	
	@RequestMapping("/index")
	public String index(){
		return "/notice/index";
	}
	
	@RequestMapping("/findNotice")
	@ResponseBody
	public List<Notice> findNotice(){
		List<Notice> list = nbsi.find(new Notice());
		List<Notice> nli = new ArrayList<Notice>();
		for (Notice notice : list) {
			if(notice.getEndDate().getTime()<System.currentTimeMillis()){
				continue;
			}
			nli.add(notice);
			if(nli.size()==5) break;
		}
		
		return nli;
	}
	
	@Override
	public List<Notice> find(Notice t) {
		return nbsi.find(t);
	}

	@Override
	public Msg insert(Notice t,
			@RequestParam(required=false,value="files") MultipartFile[] files) {
		Msg m = nbsi.insert(t);
		if(m.isIs()){
			try {
				List<Files> list= FileIOUtil.saveFile(files, "t_coc_notices", t.getId());
				for (Files file : list) {
					fbsi.insert(file);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return m;
	}
	
	@RequestMapping("/showNotice")
	public String showNotice(Integer index,HttpServletRequest req){
		List<Notice> list = nbsi.find(new Notice());
		Notice n = list.get(index);
		
		req.setAttribute("notices", list.size());
		req.setAttribute("n", n);
		req.setAttribute("i", index);
		return "/notice/showNotice";
	}
	
	@RequestMapping("/lookNotice/{nid}")
	public String lookNotice(HttpServletRequest req,@PathVariable(value="nid") Integer id){
		Notice n = new Notice();
		n.setId(id);
		n = nbsi.get(n);
		req.setAttribute("n", n);
		return "/notice/lookNotice";
	}

	
	@RequestMapping("/getNotice")
	@ResponseBody
	public Notice getNotice(Integer index){
		List<Notice> list = nbsi.find(new Notice());
		Notice n = list.get(index);
		return n;
	}
	
}
